package com.wg.msuser.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wg.msuser.entity.User;
import com.wg.msuser.entity.dto.QueryPageDto;
import com.wg.msuser.mapper.UserMapper;
import com.wg.msuser.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Transactional
public class UserService extends ServiceImpl<UserMapper, User> {
    @Autowired
    private UserMapper userMapper;

    // 注册用户
    public int registerUser(User user) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setCreateTime(sdf.format(new Date()));
        return userMapper.insert(user);
    }

    // 登录
    public User loginUser(User user) {
        QueryWrapper<User> queryWrapper = Wrappers.query();
        queryWrapper.eq("user_name", user.getUserName()).eq("pwd", user.getPwd());
        return userMapper.selectOne(queryWrapper);
    }

    // 修改用户信息
    public boolean updateUser(User user) {
        return userMapper.updateById(user) > 0;
    }

    // 删除用户
    public boolean deleteUser(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    // 查询用户(模糊查询)
    public Page<User> selectPage(User user, QueryPageDto pager){
        QueryWrapper<User> queryWrapper = Wrappers.query();// 创建查询条件
        if(user != null){
            queryWrapper.like(StringUtil.isNotEmpty(user.getUserName()), "user_name", user.getUserName());
            queryWrapper.like(StringUtil.isNotEmpty(user.getNc()), "nc", user.getNc());
            queryWrapper.like(StringUtil.isNotEmpty(user.getPhone()), "phone", user.getPhone());
            queryWrapper.like(StringUtil.isNotEmpty(user.getEmail()), "email", user.getEmail());
            queryWrapper.like(StringUtil.isNotEmpty(user.getSex()), "sex", user.getSex());
            queryWrapper.like(StringUtil.isNotEmpty(user.getStatus()), "status", user.getStatus());
            queryWrapper.like(StringUtil.isNotEmpty(user.getCreateTime()), "create_time", user.getCreateTime());
            queryWrapper.like((user.getShopCount() != null), "shop_count", user.getShopCount());
        }
        Page<User> pageInfo = userMapper.selectPage(new Page<User>(pager.getPageNum(), pager.getPageSize()), queryWrapper);
        return pageInfo;
    }

    public User getUserByUserName(String userName) {
        return userMapper.getUserByUserName(userName);
    }

    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }
}
